<template>
  <div>
    <el-container>
      <el-header style="margin-top: 10px;height: auto;">
        <el-row v-if="this.$store.getters.roles.indexOf('crm_product_manager') !== -1">
          供应商:
          <el-select
            v-model="crmsupplier_id"
            style="width: 150px;"
            filterable
            remote
            reserve-keyword
            placeholder="请输入关键词"
            :remote-method="querySearchSupplier"
            :loading="supplierloading"
          >
            <el-option
              v-for="item in suppliers"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
          <el-input
            v-model="kwInput"
            style="width: 300px"
            placeholder="输入 任意字符 进行筛选"
            class="input-with-select"
            clearable
            @keyup.native.enter="handleSearch"
          >
            <el-button slot="append" icon="el-icon-search" :loading="listLoading" @click="handleSearch">搜索</el-button>
          </el-input>
          <el-button
            type="primary"
            class="el-icon-plus add-btn"
            :disabled="listLoading"
            @click="handleAction('create', '添加')"
          >添加
          </el-button>
        </el-row>
        <el-row v-if="selected.length" style="margin-top: 5px;">
          <span>已经添加产品数量:{{ selected.length }}</span>
          <el-button type="text" title="生成报价" icon="el-icon-eye" @click="showSeletedPorductVisible=true">查看</el-button>
        </el-row>
      </el-header>
      <el-main>
        <el-table
          v-loading="listLoading"
          :data="data"
          border
          fit
          highlight-current-row
          style="width: 100%"
          @selection-change="handleSelectionChange"
          @cell-mouse-enter="(m) => m.active=true"
          @cell-mouse-leave="(m) => m.active=false"
          @sort-change="handleSort"
        >
          <el-table-column
            type="selection"
            width="55"
          />
          <el-table-column prop="images" label="产品图片" width="180">
            <template slot-scope="scope">
              <el-image
                v-if="scope.row.images.length"
                style="width: 100px; height: auto"
                :src="scope.row.images[0]"
                :preview-src-list="scope.row.images"
              />
            </template>
          </el-table-column>
          <el-table-column prop="our_sku" label="SKU" width="180">
            <template slot-scope="scope">
              <div class="editable-cell" @mouseenter="scope.row.showEditIcon = true" @mouseleave="scope.row.showEditIcon = false">
                <div v-if="scope.row.editing_sku">
                  <el-input v-model="scope.row.our_sku" size="mini" @blur="handleEdit(scope.row, 'our_sku')" @keyup.enter.native="handleEdit(scope.row, 'our_sku')" />
                </div>
                <div v-else>
                  <span style="display: block">{{ scope.row.our_sku }}</span>
                  <span style="display: block">{{ scope.row.product_category }}</span>
                  <span style="display: block">{{ scope.row.product_type }}</span>
                  <span style="display: block">{{ scope.row.model }}</span>
                  <i v-show="scope.row.showEditIcon" class="el-icon-edit" style="margin-left: 5px; cursor: pointer" @click="scope.row.editing_sku = true" />
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="parameters" label="参数" width="350">
            <template slot-scope="scope">
              <div class="editable-cell" @mouseenter="scope.row.showEditIcon = true" @mouseleave="scope.row.showEditIcon = false">
                <div v-if="scope.row.editing_params">
                  <el-input v-model="scope.row.parameters" type="textarea" size="mini" rows="4" @blur="handleEdit(scope.row, 'parameters')" />
                </div>
                <div v-else>
                  <el-tabs v-model="scope.row.activeName" tab-position="left">
                    <el-tab-pane label="中文" name="first">
                      <pre>{{ scope.row.parameters }}</pre>
                      <i v-show="scope.row.showEditIcon" class="el-icon-edit" style="margin-left: 5px; cursor: pointer" @click="scope.row.editing_params = true" />
                    </el-tab-pane>
                    <el-tab-pane label="英文" name="second">
                      <pre v-if="scope.row.parameters_en.length">{{ scope.row.parameters_en }}</pre>
                      <div v-else>
                        <el-button size="mini" @click="handleTranslate(scope.row)">翻译</el-button>
                      </div>
                    </el-tab-pane>
                  </el-tabs>
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="moq" label="MOQ" width="120">
            <template slot-scope="scope">
              <div class="editable-cell" @mouseenter="scope.row.showEditIcon = true" @mouseleave="scope.row.showEditIcon = false">
                <div v-if="scope.row.editing_moq">
                  <el-input v-model.number="scope.row.moq" size="mini" type="number" @blur="handleEdit(scope.row, 'moq')" @keyup.enter.native="handleEdit(scope.row, 'moq')" />
                </div>
                <div v-else>
                  <span>{{ scope.row.moq }}</span>
                  <i v-show="scope.row.showEditIcon" class="el-icon-edit" style="margin-left: 5px; cursor: pointer" @click="scope.row.editing_moq = true" />
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="note" label="备注信息" width="200">
            <template slot-scope="scope">
              <div class="editable-cell" @mouseenter="scope.row.showEditIcon = true" @mouseleave="scope.row.showEditIcon = false">
                <div v-if="scope.row.editing_note">
                  <el-input v-model="scope.row.note" type="textarea" size="mini" rows="3" @blur="handleEdit(scope.row, 'note')" />
                </div>
                <div v-else>
                  <span>{{ scope.row.note }}</span>
                  <i v-show="scope.row.showEditIcon" class="el-icon-edit" style="margin-left: 5px; cursor: pointer" @click="scope.row.editing_note = true" />
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column v-if="this.$store.getters.roles.indexOf('crm_product_manager') !== -1" prop="crmsupplier_infos.name" label="供应商 " width="180">
            <template slot-scope="scope">
              <span style="display: block">{{ scope.row.crmsupplier_infos.name }}</span>
              <div v-if="scope.row.crmsupplier_infos.tag.length > 0" style="display: block">
                <el-tag
                  v-for="tag in scope.row.crmsupplier_infos.tag"
                  :key="tag"
                >
                  {{ tag }}
                </el-tag></div>
            </template>
          </el-table-column>
          <el-table-column v-if="this.$store.getters.roles.indexOf('crm_product_manager') !== -1" prop="supplier_sku" label="供应商SKU" width="180" />
          <!--                <el-table-column prop="stock" label="库存量" width="120"></el-table-column>-->
          <!--                <el-table-column prop="pi_lead_period" label="PI交货周期" width="150"></el-table-column>-->
          <!--                <el-table-column prop="manufacture_lead_period" label="厂家供货周期" width="150"></el-table-column>-->
          <el-table-column prop="create_at" label="创建时间" width="180">
            <template slot-scope="scope">
              <div>{{ scope.row.create_at }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" fixed="right" label="操作" width="200">
            <template slot-scope="scope">
              <el-button size="mini" type="success" @click="handleAction('edit', scope.row)">修改</el-button>
              <el-button size="mini" type="danger" @click="handleAction('delete', scope.row)">删除</el-button>
            </template>
          </el-table-column>

        </el-table>
        <el-pagination
          v-if="data.length"
          background
          class="mt-pagination"
          :current-page="page"
          :page-sizes="[10,20,50,100]"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </el-main>
    </el-container>
    <el-dialog
      append-to-body
      :title="title"
      width="1200px"
      :visible.sync="innerDialogVisible"
      :close-on-click-modal="false"
    >
      <el-form :model="temp" label-position="right" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item v-if="this.$store.getters.roles.indexOf('crm_product_manager') !== -1" label="供应商" prop="product_type">
              <el-select
                v-model="temp.crmsupplier_id"
                filterable
                remote
                reserve-keyword
                placeholder="请输入关键词"
                :remote-method="querySearchSupplier"
                :loading="supplierloading"
              >
                <el-option
                  v-for="item in suppliers"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="产品目录" prop="product_category">
              <div style="display: flex; align-items: center;">
                <el-select v-model="temp.product_category" style="flex-grow: 0; margin-right: 10px;width: 200px;">
                  <el-option v-for="item in product_categorys" :key="item.id" :label="item.id" :value="item.name" />
                </el-select>
                <div style="flex-grow: 0;">自定义:</div>
                <el-input v-model="temp.product_category" placeholder="自定义名称" style="flex-grow: 0;width: 200px" />
              </div>
            </el-form-item>
            <el-form-item label="产品类型" prop="product_type">
              <el-input v-model="temp.product_type" placeholder="裤子，上衣等" />
            </el-form-item>
            <el-form-item label="我方SKU" prop="our_sku">
              <el-input v-model="temp.our_sku" />
            </el-form-item>
            <el-form-item label="供应商SKU" prop="supplier_sku">
              <el-input v-model="temp.supplier_sku" />
            </el-form-item>
            <el-form-item label="MOQ" prop="moq">
              <el-input v-model="temp.moq" type="number" />
            </el-form-item>
            <el-form-item label="库存量" prop="stock">
              <el-input v-model="temp.stock" type="number" />
            </el-form-item>
            <el-form-item label="PI周期" prop="pi_lead_period">
              <el-input v-model="temp.pi_lead_period" type="number" />
            </el-form-item>
            <el-form-item label="供货周期" prop="manufacture_lead_period">
              <el-input v-model="temp.manufacture_lead_period" type="number" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品型号" prop="model">
              <el-input v-model="temp.model" />
            </el-form-item>
            <el-form-item label="技术参数" prop="parameters">
              <el-input v-model="temp.parameters" type="textarea" />
            </el-form-item>
            <el-form-item label="备注信息" prop="note">
              <el-input v-model="temp.note" type="textarea" />
            </el-form-item>
            <el-form-item label="产品图片" prop="images">
              <el-image
                v-if="temp.images.length"
                style="width: 100px; height: 100px"
                :src="temp.images[0]"
                :preview-src-list="temp.images"
              />
              <crmcommonfilesmanager color="#1890ff" class="editor-upload-btn" @insert="handleInsertFile" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="innerDialogVisible = false">取 消</el-button>
        <el-button :type="action !== 'delete'?'primary':'danger'" @click="confirm">确 定</el-button>
      </span>
    </el-dialog>
    <crmquoteproduct :selected-products="selected" :visible="showSeletedPorductVisible" @close="showSeletedPorductVisible=false" />
  </div>
</template>

<script>
import { Get, Post, Put, Delete } from '@/api/crm/crmsupplierproduct'
import { Get as GetProductCategory } from '@/api/crm/crmm'
import { Get as GetSupplier } from '@/api/crm/crmsupplier'
import qs from 'qs'
import Crmcommonfilesmanager from './elements/crmCommonfilesmanager'
import Crmquoteproduct from './elements/crmquoteproduct'

const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}
export default {
  name: 'Crmcustomerproduct',
  components: { Crmquoteproduct, Crmcommonfilesmanager },
  data() {
    return {
      showSeletedPorductVisible: false,
      data: [],
      crmsupplier_id: '',
      crmsupplier_name: '',
      selected: [],
      listLoading: false,
      kwInput: '',
      order_by: '',
      order_desc: '',
      // pagination
      pagesize: 30,
      page: 1,
      total: 0,
      action: null,
      dialogVisible: false,
      title: '',
      inputVisible: false,
      inputValue: '',
      temp: {
        crmsupplier_id: '', // 供应商ID，需要与CRMSupplier关联
        product_category: '瑜伽服', // 产品类别
        product_type: '', // 产品类型
        our_sku: '', // 我方SKU
        supplier_sku: '', // 供应商SKU
        images: [], // 图片链接，以逗号分隔
        moq: 1, // 最小订单数量
        stock: 1, // 库存量
        model: '', // 产品型号
        parameters: '', // 技术参数等其他信息
        pi_lead_period: 3, // PI交货周期天
        manufacture_lead_period: 3, // 厂家供货周期
        note: '' // 其他备注信息
      },
      product_categorys: [],
      width: '',
      innerDialogVisible: false,
      suppliers: [],
      supplierloading: false,
      options: [],
      loading: false
    }
  },
  created() {
    this.crmsupplier_id = this.$route.query.id
    this.crmsupplier_name = this.$route.query.name
    this.handleGetProductCategory()
    this.getList()
  },
  methods: {
    handleEdit(row, field) {
      // Reset editing state
      row[`editing_${field}`] = false

      // Prepare data for update
      const updateData = {
        id: row.id,
        [field]: row[field]
      }

      // Call API to update
      Put(row.id, updateData).then(() => {
        this.notify(`更新${field}成功`)
        if (field === 'parameters') {
          // Clear English translation when Chinese parameters are updated
          row.parameters_en = ''
        }
      }).catch(err => {
        console.error(err)
        this.notify(`更新失败: ${err.message}`, 'error')
        // Revert changes if update fails
        this.getList()
      })
    },
    querySearchSupplier(queryString) {
      this.supplierloading = true
      GetSupplier(null, qs.stringify({
        kw: queryString,
        pagesize: 100,
        page: 1
      }))
        .then(response => {
          this.suppliers = response.data.data
          this.supplierloading = false
        }).catch(err => {
          console.log(err)
          this.supplierloading = false
        })
    },
    handleInsertFile(item) {
      this.temp.images.push(item.url)
    },
    handleClose(tag) {
      this.temp.tag.splice(this.temp.tag.indexOf(tag), 1)
    },

    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    handleInputConfirm() {
      const inputValue = this.inputValue
      if (inputValue) {
        this.temp.tag.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    resetTemp() {
      this.temp = {
        crmsupplier_id: '', // 供应商ID，需要与CRMSupplier关联
        product_category: '瑜伽服', // 产品类别
        product_type: '', // 产品类型
        our_sku: '', // 我方SKU
        supplier_sku: '', // 供应商SKU
        images: [], // 图片链接，以逗号分隔
        moq: 1, // 最小订单数量
        stock: 1, // 库存量
        model: '', // 产品型号
        parameters: '', // 技术参数等其他信息
        pi_lead_period: 3, // PI交货周期天
        manufacture_lead_period: 3, // 厂家供货周期
        note: '' // 其他备注信息
      }
    },
    handleGetProductCategory() {
      GetProductCategory(null, qs.stringify({
        pagesize: 100,
        table_name: 'CRMProductCategory',
        page: 1,
        order_by: this.order_by,
        order_desc: this.order_desc
      }))
        .then(response => {
          this.product_categorys = response.data.data
        }).catch(err => {
          console.log(err)
        })
    },
    handleTranslate(row) {
      Get(row.id, qs.stringify({
        t_parameters: 1
      }))
        .then(response => {
          row.parameters_en = response.data.parameters_en
        }).catch(err => {
          console.log(err)
        })
    },
    getList() {
      this.listLoading = true
      Get(null, qs.stringify({
        kw: this.kwInput,
        crmsupplier_id: this.crmsupplier_id,
        pagesize: this.pagesize,
        page: this.page,
        order_by: this.order_by,
        order_desc: this.order_desc
      }))
        .then(response => {
          this.scrollTop()
          this.data = response.data.data.map(v => ({
            ...v,
            activeName: 'first',
            showEditIcon: false,
            editing_sku: false,
            editing_params: false,
            editing_moq: false,
            editing_note: false
          }))
          this.listLoading = false
          this.total = response.data.total
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    handleAction(action, row) {
      this.action = action
      switch (action) {
        case 'create':
          this.width = '50%'
          this.title = '添加新产品'
          this.resetTemp()
          this.innerDialogVisible = true
          break
        case 'delete':
          this.width = '30%'
          this.title = `确认要删除客户:${row.name}?`
          this.temp = Object.assign({}, row)
          this.innerDialogVisible = true
          break
        case 'edit':
          this.width = '50%'
          this.title = `上传产品:${row.name}`
          Object.keys(this.temp).forEach(key => {
            if (row[key] !== undefined) this.temp[key] = row[key]
          })
          this.temp.id = row.id
          this.innerDialogVisible = true
          break
      }
    },
    confirm() {
      const _data = this.temp
      switch (this.action) {
        case 'create':
          Post(_data
          ).then(response => {
            this.innerDialogVisible = false
            this.getList()
            this.notify('添加成功')
          })
          break
        case
          'delete'
          :
          Delete(_data.id).then((response) => {
            this.innerDialogVisible = false
            this.getList()
            this.$emit('reload')
            this.notify('删除成功')
          })
          break
        case
          'edit'
          :
          Put(_data.id, _data).then((response) => {
            this.innerDialogVisible = false
            this.getList()
            this.notify('更新成功')
          })
          break
      }
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    // 点击搜索
    handleSearch() {
      this.page = 1
      this.getList()
    },
    generateHtmlTable() {
      // 开始构建表格的HTML代码
      let html = '<table border="1">'
      html += '<tr><th>Image</th><th>Info</th><th>SKU</th></tr>' // 表头

      // 遍历selected数组，为每个项目构建表格行
      this.selected.forEach(item => {
        const images = item.images || []
        // 添加新的行
        html += '<tr>'

        // 添加图片列，这里假设images是一个包含图片URL的数组
        // 为简化起见，只展示第一张图片
        if (images.length > 0) {
          html += `<td><img src="${images[0]}" alt="Image" style="width:100px;height:auto;"></td>`
        } else {
          html += '<td>No Image</td>'
        }

        // 添加参数列
        const parametersEn = (item.parameters_en || '').replace(/\n/g, '<br>')
        html += `<td>${parametersEn}</td>`
        html += `<td>${item.our_sku}</td>`

        html += '</tr>'
      })

      html += '</table>'
      navigator.clipboard.writeText(html).then(() => {
        this.notify('表格已经复制到剪切板，写邮件时候直接粘贴')
      }).catch(err => {
        console.error('复制到剪贴板失败:', err)
      })
      console.log(html)
      return html
    },
    handleSelectionChange(val) {
      val.forEach((item) => {
        if (!this.selected.some((selectedItem) => selectedItem.sku === item.our_sku)) {
          // 如果没有重复项，则添加对象到数组
          if (item.parameters_en.length === 0) {
            this.handleTranslate(item)
          }
          const new_item = {
            images: item.images,
            sku: item.our_sku,
            parameters: item.parameters,
            parameters_en: item.parameters_en,
            price: 0,
            currency: 'USD',
            moq: 100,
            activeName: 'first'
          }
          this.selected.push(new_item)
        } else {
          // 如果有重复项，可以在这里处理，例如通知用户
          this.notify('该数据已经添加')
        }
      })
      console.log(this.selected)
    },
    handleRemoveFromList(row) {
      this.selected = this.selected.filter(item => item.id !== row.id)
    },
    handleSort(v) {
      this.order_by = v.prop
      this.order_desc = orderMapper[v.order]
      this.getList()
    },
    scrollTop() {
      window.scrollTo(0, 0)
    }
  }
}
</script>

<style scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}

.top >>> .el-select .el-input {
  width: 350px;
}

.top >>> .input-with-select .el-input-group__prepend {
  background-color: #fff;
}

.top {
  padding-left: 20px;
  margin-bottom: 30px;
  margin-top: 28px;
}

.input-with-select {
  width: calc(100% - 200px);
}

.add-btn {
  float: right;
  margin-right: 20px;
  width: 150px
}

.mt-pagination {
  float: right;
  margin-top: 5px;
}

.app-container >>> .el-dialog {
  margin-top: 48px !important;
  margin-bottom: 68px;
}

.mt-dialog >>> .el-transfer-panel {
  width: calc(50% - 60px);
}

.mt-form >>> .el-select {
  width: 100%;
}

.mt-form >>> .el-input__inner {
  width: 100%;
}

.mt-dialog >>> .el-dialog {
  margin-top: 60px;
  /*margin: 168px auto !important;*/
}

.mt-dialog >>> .el-dialog__body {
  padding-bottom: 100px;
}

.editable-cell {
  position: relative;
}
.editable-cell:hover .el-icon-edit {
  display: inline-block;
}
</style>
